package controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.logging.Logger;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.DataAccessor;

public class Admin extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static Logger theLogger = Logger.getLogger("Admin");
	
	private static String driver 		= "com.mysql.jdbc.Driver";
	private static String dsn 			= "jdbc:mysql://localhost/record_manager";
	private static String namespace 	= "";
	private static String dbuser 		= "root";
	private static String dbpwd 		= "root";
	
	private DataAccessor dataAccessor = null;
	public void init(ServletConfig config) throws ServletException {
    	super.init(config);    	
    	
    	theLogger.info("Admin loading....record_Manager");
    	initializeDatabase();
    	dataAccessor = DataAccessor.getInstance();    	
    	theLogger.info("Admin started successfully. record_Manager...");
   	}
	
	 /**
     * This will read the data from the web.xml and load into the local objects.
     */
    public void initializeDatabase() {
		dsn = getServletContext().getInitParameter("jdbc:subprotocol:subname");
		driver = getServletContext().getInitParameter("driver");
		namespace = getServletContext().getInitParameter("namespace");
		dbuser = getServletContext().getInitParameter("username");
		dbpwd = getServletContext().getInitParameter("password");
		
		theLogger.info("dsn: " + dsn + " driver: " + driver + " namespace: " + namespace + " dbuser: " + dbuser + " dbpwd: " + dbpwd);
	}
    
    public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
    	doPost(request, response);
    }
    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    	throws IOException, ServletException {
    	
      	String method = request.getParameter("method");	
      	if(method == null)
      		return;

    	// response.setContentType("text/html");
      	PrintWriter out = response.getWriter();      	
      System.out.println("working............");
      	dataAccessor = DataAccessor.getInstance();
  		theLogger.info("method: " + method);
  	
  		if(DataAccessor.LOGIN.equals(method)) {
  			String userName = request.getParameter("username");	
  	      	String password = request.getParameter("password");	
  	      	String login_type = request.getParameter("login_type");	
  	      	
  			String validation = dataAccessor.validateUser(userName, password, login_type);
  			theLogger.info("Validation result is "+validation);
  			
  			if(validation.equals("Invalid")) {
  			out.print("Invalid user name or password.");  				
  			
  			} else if(validation.equals("Disabled")) { 
  				out.print("User is currently disabled.");  		
  			
  			} else { // -@#-
  				theLogger.info("User Validation");
  				
  				int index = validation.indexOf("-@#-");
  				int userId = Integer.parseInt(validation.substring(0, index));
  				
  				validation = validation.substring(index + 4, validation.length());
  				
  				index = validation.indexOf("-@#-");
  				String firstName = validation.substring(0, index);
  				validation = validation.substring(index + 4, validation.length());
  				
  				index = validation.indexOf("-@#-");
  				String lastName = validation.substring(0, index);
  				validation = validation.substring(index + 4, validation.length());
  				
  				index = validation.indexOf("-@#-");
  				String dbIsEnabled = validation.substring(0, index);
  				validation = validation.substring(index + 4, validation.length());
  				
  				int userLevel = Integer.parseInt(validation);
  				
  				/*Calendar calendar = Calendar.getInstance();
  				int selectedYear = calendar.get(Calendar.YEAR);*/
  				int selectedYear = DataAccessor.getInstance().getConfiguredYear();
  				HttpSession session = request.getSession();
  				session.setAttribute("userId", userId);
  				session.setAttribute("firstName", firstName);
  				session.setAttribute("lastName", lastName);
  				session.setAttribute("dbIsEnabled", dbIsEnabled);
  				session.setAttribute("userLevel", userLevel);
  				session.setAttribute("login_type", login_type);
  				session.setAttribute("selectedYear", selectedYear);
  				session.setAttribute("classDetailId", -1);
  				
  				if(login_type.equals("Student")) {
  					HashMap<String, String> hashMap = dataAccessor.getStudentProgram(userId);
  					session.setAttribute("programId", hashMap.get("program_id"));
  					session.setAttribute("programName", hashMap.get("program_name"));
  					session.setAttribute("Enrollment_Number", hashMap.get("Enrollment_Number"));
  					
  				} else if(login_type.equals("Administrator")) {
  					
  				} else if(login_type.equals("Evaluator")) {
  					
  				} 
  				
  				out.print('1');
  			}
  		} else if(DataAccessor.DELETEUSER.equals(method)) {
  			int userId = Integer.parseInt(request.getParameter("userId"));       			
  			dataAccessor.deleteUser(userId);
      	} else if(DataAccessor.SAVEUSER.equals(method)) {
      		try {
      			HttpSession session = request.getSession();
          		
      			int sessionUserId = ((Integer)session.getAttribute("userId")).intValue();
      			int userId = Integer.parseInt(request.getParameter("userId"));
      			
      			String firstName = request.getParameter("firstName");
          		String lastName = request.getParameter("lastName");
      			String userName = request.getParameter("userName");	
              	String userPassword = request.getParameter("userPassword");
              	int userLevel = Integer.parseInt(request.getParameter("userLevel"));
              	int enabled = Integer.parseInt(request.getParameter("enabled")); 
              	
          		String phoneMobile = request.getParameter("phoneMobile");
          		String emailAddress = request.getParameter("emailAddress"); 
          		String description = request.getParameter("description");
 
          		String result = dataAccessor.saveUser(sessionUserId, userId, firstName, lastName, userName, userPassword, userLevel, enabled, phoneMobile, emailAddress, description);
          		out.print(result);
          		
      		} catch(Exception e) {
      			System.out.println("Exception in SAVEUSER: " + e.toString());
      		}
      	} else if(DataAccessor.DELETECLASS.equals(method)) {
      		try {
  			int classDetailId = Integer.parseInt(request.getParameter("classDetailId")); 
      		dataAccessor.deleteClass(classDetailId);
      		} catch(Exception e) {
      			System.out.println("Exception in DELETECLASS: " + e.toString());
      		}
      	} else if(DataAccessor.VERIFYCLASSID.equals(method)) {
  			int classId = Integer.parseInt(request.getParameter("classId"));       			
  			out.print( dataAccessor.verifyClassId(classId));
      	} else if(DataAccessor.VERIFYCLASSCODE.equals(method)) {
  			String classCode = request.getParameter("classCode");       			
  			out.print( dataAccessor.verifyClassCode(classCode));
      	} else if(DataAccessor.SAVECLASS.equals(method)) {
      		try {
      			HttpSession session = request.getSession();
      			int sessionUserId = ((Integer)session.getAttribute("userId")).intValue();
      			int selectedYear = ((Integer)session.getAttribute("selectedYear")).intValue();
      			int id = Integer.parseInt(request.getParameter("id"));
      			int classDetailId =  Integer.parseInt(request.getParameter("classDetailId"));
      			int classId = Integer.parseInt(request.getParameter("classId"));
      			String className = request.getParameter("className");
          		int enabled = Integer.parseInt(request.getParameter("enabled"));
          		double classFee = Double.parseDouble(request.getParameter("classFee"));
          		int year = Integer.parseInt(request.getParameter("year"));
          		String description = request.getParameter("description");
          		dataAccessor.saveClass(sessionUserId, id, classDetailId, classId, className, enabled, classFee, year, selectedYear, description);
      		} catch(Exception e) {
      			System.out.println("Exception in SAVECLASS: " + e.toString());
      		}
      	} else if(DataAccessor.SAVESTUDENT.equals(method)) {
      		try {
      			HttpSession session = request.getSession();
      			int sessionUserId = ((Integer)session.getAttribute("userId")).intValue();
      			int studentFeeId = Integer.parseInt(request.getParameter("studentFeeId"));
      			String rollNumber = request.getParameter("rollNumber");
      			int classDetailId =((Integer)session.getAttribute("classDetailId")).intValue();
      			String name = request.getParameter("name");
      			String fatherName = request.getParameter("fatherName");
          		String motherName = request.getParameter("motherName");
          		String address1 = request.getParameter("address1");
          		String address2 = request.getParameter("address2");
          		String mobile = request.getParameter("mobile");
          		String phone = request.getParameter("phone");
          		double totalFee = Double.parseDouble(request.getParameter("totalFee"));
          		String dob = request.getParameter("dob"); 
          		String description = request.getParameter("description");
          		
          		dataAccessor.saveStudent(sessionUserId, studentFeeId, rollNumber, classDetailId, name, fatherName, motherName, address1, address2, mobile, phone, totalFee, dob, description);
      		} catch(Exception e) {
      			System.out.println("Exception in SAVESTUDENTwetrwet: " + e.toString());
      		}
    	} else if(DataAccessor.SAVESTUDENTFEE.equals(method)) {
      		try {
      			HttpSession session = request.getSession();
      			int sessionUserId = ((Integer)session.getAttribute("userId")).intValue();
      			int studentFeeId = Integer.parseInt(request.getParameter("studentFeeId"));
      			
      			String recieptNumber = request.getParameter("recieptNumber");
      			double feePay = Double.parseDouble(request.getParameter("feePay"));
      			String feeType = request.getParameter("feeType");
          		String feeRemark = request.getParameter("feeRemark");
          		
          		dataAccessor.saveStudentFee(sessionUserId, studentFeeId, recieptNumber, feePay, feeType, feeRemark);
      		} catch(Exception e) {
      			System.out.println("Exception in SAVESTUDENTFEE: " + e.toString());
      		}
    	} else if(DataAccessor.DELETESTUDENT.equals(method)) {
      		try {
      			HttpSession session = request.getSession();
      			int sessionUserId = ((Integer)session.getAttribute("userId")).intValue();
      			int studentFeeId = Integer.parseInt(request.getParameter("studentFeeId"));
      			String rollNumber = request.getParameter("rollNumber");
      			
          		dataAccessor.deleteStudent(sessionUserId, studentFeeId, rollNumber);
      		} catch(Exception e) {
      			System.out.println("Exception in DELETESTUDENT: " + e.toString());
      		} 
    	} else if(DataAccessor.DELETESTUDENTFEEDETAILS.equals(method)) {
      		try {
      			HttpSession session = request.getSession();
      			int sessionUserId = ((Integer)session.getAttribute("userId")).intValue();
      			int studentFeeId = ((Integer)session.getAttribute("studentFeeId")).intValue();
      			int feeId = Integer.parseInt(request.getParameter("feeId"));
      			
          		dataAccessor.deleteStudentFeeDetails(sessionUserId, studentFeeId, feeId);
      		} catch(Exception e) {
      			System.out.println("Exception in DELETESTUDENTFEEDETAILS: " + e.toString());
      		}
    	} else if(DataAccessor.UPGRADESTUDENT.equals(method)) {
      		try {
      			HttpSession session = request.getSession();
      			int sessionUserId = ((Integer)session.getAttribute("userId")).intValue();
      			String rollNumber =request.getParameter("rollNumber");
      			int year = Integer.parseInt(request.getParameter("selectedYear"));
      			int classDetailId = Integer.parseInt(request.getParameter("classDetailId"));
          		String result = dataAccessor.upgradeStudent(sessionUserId, rollNumber, classDetailId, year);
          		out.print(result);
      		} catch(Exception e) {
      			System.out.println("Exception in UPGRADESTUDENT: " + e.toString());
      		}
    	} else if(DataAccessor.SAVEQUICKLINK.equals(method)) {
      		try {
      			HttpSession session = request.getSession();
      			int sessionUserId = ((Integer)session.getAttribute("userId")).intValue();
      			int selectedYear = ((Integer)session.getAttribute("selectedYear")).intValue();
      			int quickLink1 = Integer.parseInt(request.getParameter("quickLink1"));
      			int quickLink2 = Integer.parseInt(request.getParameter("quickLink2"));
      			int quickLink3 = Integer.parseInt(request.getParameter("quickLink3"));
      			int quickLink4 = Integer.parseInt(request.getParameter("quickLink4"));
      			int quickLink5 = Integer.parseInt(request.getParameter("quickLink5"));
      			int quickLink6 = Integer.parseInt(request.getParameter("quickLink6"));
      			
          		dataAccessor.saveQickLink(sessionUserId, selectedYear, quickLink1, quickLink2, quickLink3, quickLink4, quickLink5, quickLink6);
      		} catch(Exception e) {
      			System.out.println("Exception in SAVEQUICKLINK: " + e.toString());
      		}
      		
      	} else if(DataAccessor.VERIFYQUICKLINK.equals(method)) {
      		try {
      			HttpSession session = request.getSession();
      			int sessionUserId = ((Integer)session.getAttribute("userId")).intValue();
      			int selectedYear = ((Integer)session.getAttribute("selectedYear")).intValue();
      			int classId = Integer.parseInt(request.getParameter("classId"));
          		String result = dataAccessor.verifyQickLink(sessionUserId, selectedYear, classId);
          		out.print(result);
      		} catch(Exception e) {
      			System.out.println("Exception in SAVEQUICKLINK: " + e.toString());
      		}
      	} else if(DataAccessor.CONFIGUREYEAR.equals(method)) {
      		try {
      			HttpSession session = request.getSession();
      			int sessionUserId = ((Integer)session.getAttribute("userId")).intValue();
      			int yearConfig = Integer.parseInt(request.getParameter("yearConfig"));
          		dataAccessor.configureYear(sessionUserId, yearConfig);
      		} catch(Exception e) {
      			System.out.println("Exception in SAVEQUICKLINK: " + e.toString());
      		}
      		
      	} else if(DataAccessor.SAVEEXPENSES.equals(method)) {
      		try {
      			int id = -1;
      			if(request.getParameter("expensesId") != null) {
      				id = Integer.parseInt(request.getParameter("expensesId"));
      			}
      			HttpSession session = request.getSession();
      			int sessionUserId = ((Integer)session.getAttribute("userId")).intValue();
      			
      			String paidTo = request.getParameter("paidTo");
      			String dateAdded = request.getParameter("dateAdded");
      			double amount = 0.0;
      			if(request.getParameter("amount") != null) {
      				amount = Double.parseDouble(request.getParameter("amount"));
      			}
      			
      			String purpose = request.getParameter("purpose");
      			dataAccessor.saveExpenses(id, paidTo, dateAdded, purpose, sessionUserId, amount);
      		} catch(Exception e) {
      			System.out.println("Exception in SAVEQUICKLINK: " + e.toString());
      		}
      		
      	} else if(DataAccessor.DELETEEXPENSES.equals(method)) {
      		try {
      			int id = -1;
      			if(request.getParameter("expensesId") != null) {
      				id = Integer.parseInt(request.getParameter("expensesId"));
      			}
      			
      			dataAccessor.deleteExpenses(id);
      		} catch(Exception e) {
      			System.out.println("Exception in SAVEQUICKLINK: " + e.toString());
      		}
      	}
  		
    }
    
	/**
	 * @return the driver
	 */
	public static String getDriver() {
		return driver;
	}

	/**
	 * @return the dsn
	 */
	public static String getDsn() {
		return dsn;
	}

	/**
	 * @return the namespace
	 */
	public static String getNamespace() {
		return namespace;
	}

	/**
	 * @return the dbuser
	 */
	public static String getDbuser() {
		return dbuser;
	}

	/**
	 * @return the dbpwd
	 */
	public static String getDbpwd() {
		return dbpwd;
	}
}